
/**
 * DivX Plus Web Player Javascript Library
 *
 * @file		dwpJsLib.js
 * @version		0.75
 * @author 		DivX Inc.
 * @copyright 	Copyright (c) 2010, DivX Inc.
 * @link		http://developer.divx.com/
 */
/*  Check if jQuery is already loaded and load it isn't */
if (typeof jQuery == 'undefined') {
    document.write("<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.1.min.js'></script>");
}

/**
 * Add Prototype method to String
 * This method return an object containing the parsed version from the String
 *
 * Usage Example:
 *
 * 		var myVersionStr="1.0.3.275";
 * 		var myVersionObj=myVersionStr.versionStringToObject();
 *
 * 		for (var k in myVersionObj) {
 * 			document.write(k + '=' + myVersionObj[k]);
 * 		}
 *
 *  Will return:
 *
 *  	major=1 minor=0 patch=3 build=275
 *
 */
String.prototype.versionStringToObject = function(){
    var x = this.split('.');
    // parse from string or default to 0 if can't parse
    var maj = parseInt(x[0]) || 0;
    var min = parseInt(x[1]) || 0;
    var pat = parseInt(x[2]) || 0;
    var bui = parseInt(x[3]) || 0;
    return {
        major: maj,
        minor: min,
        patch: pat,
        build: bui,
    }
}

/**
 * Add Prototype method to String
 * This method return true if the string containing a version meet minimumVersion provided as a parameter
 *
 * Usage Example:
 *
 * 		var myVersionStr="1.1.3.275";
 *
 * 		document.write(myVersionStr.StringVersionMeetMinimum('1.0');
 *
 *  Will return:
 *
 *  	true
 *
 */
String.prototype.StringVersionMeetMinimum = function(versionReference){
    minimum = versionReference.versionStringToObject();
    running = this.versionStringToObject();
    if (running.major != minimum.major) 
        return (running.major > minimum.major);
    else {
        if (running.minor != minimum.minor) 
            return (running.minor > minimum.minor);
        else {
            if (running.patch != minimum.patch) 
                return (running.patch > minimum.patch);
            else {
                if (running.build != minimum.build) 
                    return (running.build > minimum.build);
                else 
                    return true;
            }
        }
    }
}

/**
 * Will hold collection of all embeds in the page
 */
function DwpEmbedCollection(){
    this.embedList = [];
    this.currentlyPlaying;
    this.showAdOffsetSeconds;
    
    this.initAllCallbacks = function(){
        for (a = 0; a < this.embedList.length; a++) {
            if (this.embedList[a].plugin == null) {
                this.embedList[a].initCallback(a);
            }
        }
    }
}

/* The collection containing all embed in the page is held in this object */
var dwpEmbedCollection = new DwpEmbedCollection();

function dwpPlayer(embedWidth, embedHeight){

    /* Initialize private variables */
    var libraryURL = 'http://divxweb.googlecode.com/files/';
    //var fauxImages = libraryURL + 'images/'; // Set folder (or URL prefix) for images
    var fauxImages = libraryURL; //Googlecode doesnt allow folder creation
    var userAgent = navigator.userAgent;
    
    
    /* Initialize public variables */
    this.embedDiv;
    this.playerContainer;
    this.embedCollectionId;
    this.timeLeft = 0;
    
    /* Embed Parameters */
    this.width = embedWidth;
    this.height = embedHeight;
    this.url;
    this.mode;
    this.minVersion;
    this.allowContextMenu;
    this.autoPlay;
    this.loop;
    this.bannerEnabled;
    // this.bufferingMode; /* Deprecated */
    this.movieTitle;
    this.previewMessage;
    this.previewMessageSize;
    this.previewImage;
    this.enableDebug;
    this.videoResumeOverlayText
    this.isFullScreen = false; //used to determine if need to return in full screen after ad finish
    /* Ad Section */
    this.adUnitId;
    this.adServer;
    this.adType;
    this.adHtmlCode;
    this.adContainer;
    this.adDuration;
    this.adStartOffsetSeconds;
    this.adStartOffsetPercent;
    this.adRequestUrl;
    this.enableAdvertisement;
    
    /* Google Analytics */
    this.enableAnalytics;
    this.googleAnalyticsId;
    this.adCampaign;
    this.adLanguage;
    this.pageTracker;
    this.adShown = false;
    
    
    /* will hold the plugin object */
    this.plugin;
    
    /* Add inline CSS styles */
    /* fauxPlayer style */
    var styles = ".fauxPlayer { position: relative; }" +
    ".popupHolder { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: block; }" + /* Used for centering */
    ".popup { position: absolute; top:0; bottom:0; left:0; right:0; margin: auto; height: 150px; width: 300px; } " + /* Centering */
    ".popup { font-family: Calibri, Arial, Sans-Serif; font-size: 12px; color: White; border: }" +
    ".popup img.dialog { position: absolute; top: 0; left: 0; z-index: 10; display: block; }" +
    ".popup .message { width: 260px; height: 150px; position: absolute; top: 0; left: 20px; z-index: 20; }" +
    ".popup .message h1 { font-size: 16px; margin: 10px 0 0 0 !important; padding: 0 !important; color: white !important; background: none !important; }" +
    ".popup .message p {font-size: 12px;line-height:100%;  color: white !important; }" +
    ".popup .message input { font-size: 12px; background: !important; border: !important; }" +
    ".previewImage { display: block; }" +
    ".bar { width: 100%; height: 20px; margin: 0; padding: 0; position: relative; background-image: url(" +
    fauxImages +
    "dwp-progress-light.png); }" +
    ".barLeft { position: absolute; left: 0; top: 0; }" +
    ".barRight { position: absolute; right: 0; top: 0; }" +
    ".directLink img { border: 0 none !important; margin: 0 !important; padding: 0 !important; }";
    
    /* PS3 specific styles */
    if (this.type == 'ps3') {
        styles += ".popupHolder { text-align: center !important; }" +
        ".popup { position: static !important; margin-top: 8% !important; }" +
        ".popup img.dialog { position: static !important; }";
    }
    
    styles += '.btn_download a:hover{color: #97c2ca; text-decoration: underline;}' +
    '.btn_download a:link, .btn_download a:visited {background-color: transparent;background-image: url("' +
    fauxImages +
    'btn_std_download_lt.png"); background-repeat: no-repeat; height: 44px;line-height: 48px;' +
    'color: #ffffff;text-decoration: none;font-size: 14px;text-align: center;display: block;padding-top: 0pt;' +
    'padding-right: 7px;padding-bottom: 0pt;padding-left: 45px;float: left;}';
    
    /* Ad section style */
    styles += ".divjsAdContainer { position: absolute; overflow: hidden; text-align: center; display: none; float: left; z-index:5; }" +
    ".divjsPlayerContainer { position: relative; float: left; } " +
    ".divjsAdContainer a img { border: none; }" +
    ".timeLeftMessage { position: absolute; top: 400px; left: 0px; width: 100%; letter-spacing: -1px; color: white;" +
    "                   font: 24px / 45px Berlin Sans FB, Sans-Serif; background: #4A4D4A; padding: 10px; -khtml-opacity:0.6; opacity: 0.6; line-height:90%; }" +
    ".dwpDebugConsoleHeader { font-size: 150%; width: 700px; font-weight:bolder; margin:5px 0 5px 0; text-align:center; }" +
    ".dwpjsConsole { background-color:000000; color:lime; width: 700px; height: 200px; overflow: scroll; }";
    
    document.write("<style type='text/css'>" +
    styles +
    "</style>");
    
    /* Creates the appropriate "player" based on device */
    this.create = function(divToUpdate){
        /* Detect Style if required */
        this.type = this.type.toLowerCase();
        
        if (this.type != 'mobile' && this.type != 'ps3') {
            this.detectBrowser();
        }

        /* Plug-in detection */
        plug = this.detectWebPlayerPlugin();
        
        if ((this.type != 'mobile' && this.type != 'ps3' && this.type != 'linux') &&
        (Boolean(plug.installed) != true || plug.version.StringVersionMeetMinimum('2.0.2') != true)) {
            htmlCode = this.offerWebPlayerDownload(plug.installed);
        }
        else {
        
        
            this.loadBit_ly(this.bitlyLogin, this.bitlyAPIkey);
            if (!document.body && (this.enableAdvertisement == true || this.enableAdvertisement == 'true')) {
                this.enableAdvertisement = false;
                document.write('<h2><b>Error! </b>the document doesnt have body tags, advertisement will not work.</h2>');
            }
            if (this.adServer) 
                this.enableAdvertisement = true;
            this.embedDiv = divToUpdate;
            this.playerContainer = divToUpdate + '_player';
            this.adContainer = divToUpdate + '_ad';
            this.setMissingValues();
            this.embedCollectionId = dwpEmbedCollection.embedList.length;
            dwpEmbedCollection.embedList[this.embedCollectionId] = this;
            if (this.enableAnalytics == true || this.enableAnalytics == 'true') {
                try {
                    this.pageTracker = _gat._getTracker(this.googleAnalyticsId);
                    this.pageTracker._trackPageview();
                } 
                catch (err) {
                    this.enableAnalytics = false;
                    document.write('<h2><b>Error! </b>Google Analytics cannot be activated, make sure "ga.js" is loaded.</h2>');
                }
            }
            this.type = this.type.toLowerCase();
            switch (this.type) {
                case 'linux':
                    htmlCode = this.createLinuxPlayer();
                    if (this.pageTracker) {
                        /* Ping analytics */
                        this.pageTracker._trackEvent('DivX Plus Embed', 'LINUX_EMBED_DISPLAYED', this.url);
                    }                
                
                break;
                case 'ps3':
                    htmlCode = this.createPS3Player();
                    if (this.pageTracker) {
                        /* Ping analytics */
                        this.pageTracker._trackEvent('DivX Plus Embed', 'PS3_EMBED_DISPLAYED', this.url);
                    }
                    break;
                    
                    
                case 'mobile':
                    htmlCode = this.createMobilePlayer();
                    if (this.pageTracker) {
                        /* Ping analytics */
                        this.pageTracker._trackEvent('DivX Plus Embed', 'MOBILE_EMBED_DISPLAYED', this.url);
                    }
                    break;
                    
                default:
                case 'standard':
                    this.type = 'standard';
                    htmlCode = this.createStandardPlayer();
                    if (this.pageTracker) {
                        /* Ping analytics */
                        this.pageTracker._trackEvent('DivX Plus Embed', 'STANDARD_EMBED_DISPLAYED', this.url);
                    }
                    break;
            }
            
        }
        
        this.setDivDimension(divToUpdate);
        if (this.enableDebug == true || this.enableDebug == 'true') 
            htmlCode += "<div class='dwpDebugConsoleHeader'>Debug Console</div><textarea class='dwpjsConsole' id='" + this.embedDiv + "_dwpjsConsole'/>";
        this.populateDiv(divToUpdate, htmlCode);
        dwpEmbedCollection.embedList[this.embedCollectionId] = this;
        if (this.type == 'standard' && (this.enableAdvertisement == true || this.enableAdvertisement == 'true')) {
            this.loadAdUnit(this.embedCollectionId);
        }
    }
    
    /* Faux DWP for PS3 devices */
    this.createPS3Player = function(){
    
        /* Error handling for no previewImage being specified */
        if (this.previewImage == null || this.previewImage.length == 0) {
            var previewImageCode = '<img src="' + fauxImages + 'no-preview-image.png" width="100%" class="previewImage"/>';
        }
        else {
            var previewImageCode = '<img src="' + this.previewImage + '" width="100%" class="previewImage"/>';
        }
        
        /* Error handling for playing back MKV files */
        if (this.url.substr(this.url.length - 3, 3) == "mkv") {
            var popupMessage = "<h1>Save Video For Later</h1>" +
            "<p>This devices does not support playback of DivX Plus (.mkv) files. Tweet this video to watch it later or share with your friends.</p>" +
            "<input type='button' value='Tweet' onclick='tweetThis()' class='tweetThis'>";
            var popupDialog = fauxImages + 'popup-dialog.png';
            var PS3Player = '<div style="width: ' + this.width + 'px;" class="fauxPlayer">' +
            '<a class="directLink">' +
            '<div class="popupHolder">' +
            '<div class="popup">' +
            '<div class="message">' +
            popupMessage +
            '</div>' +
            '<img src="' +
            fauxImages +
            'popup-dialog.png" class="dialog">' +
            '</div>' +
            '</div>' +
            previewImageCode +
            '<div class="bar">' +
            '<img src="' +
            fauxImages +
            'dwp-bar-left.png" class="barLeft">' +
            '<img src="' +
            fauxImages +
            'dwp-bar-right.png" class="barRight">' +
            '</div>' +
            '</a>' +
            '</div>';
        }
        else {
            var href = 'href="' + this.url + '"';
            var popupDialog = fauxImages + 'click-to-play.png';
            var PS3Player = '<div style="width: ' + this.width + 'px;" class="fauxPlayer">' +
            '<a class="directLink" ' +
            href +
            '>' +
            '<div class="popupHolder">' +
            '<div class="popup">' +
            '<div class="message">' +
            '</div>' +
            '<img src="' +
            fauxImages +
            'click-to-play.png" class="dialog">' +
            '</div>' +
            '</div>' +
            previewImageCode +
            '<div class="bar">' +
            '<img src="' +
            fauxImages +
            'dwp-bar-left.png" class="barLeft">' +
            '<img src="' +
            fauxImages +
            'dwp-bar-right.png" class="barRight">' +
            '</div>' +
            '</a>' +
            '</div>';
        }
        
        return PS3Player;
    }
    /* Faux DWP for Linux Browser */
    this.createLinuxPlayer = function(){
    
        /* Error handling for no previewImage being specified */
        if (this.previewImage == null || this.previewImage.length == 0) {
            var previewImageCode = '<img src="' + fauxImages + 'no-preview-image.png" width="100%" class="previewImage"/>';
        }
        else {
            var previewImageCode = '<img src="' + this.previewImage + '" width="100%" class="previewImage"/>';
        }
        
        var href = 'href="' + this.url + '"';
        var popupDialog = fauxImages + 'click-to-play.png';
        var PS3Player = '<div style="width: ' + this.width + 'px;" class="fauxPlayer">' +
        '<a class="directLink" ' +
        href +
        '>' +
        '<div class="popupHolder">' +
        '<div class="popup">' +
        '<div class="message">' +
        '</div>' +
        '<img src="' +
        fauxImages +
        'click-to-download.png" class="dialog">' +
        '</div>' +
        '</div>' +
        previewImageCode +
        '<div class="bar">' +
        '<img src="' +
        fauxImages +
        'dwp-bar-left.png" class="barLeft">' +
        '<img src="' +
        fauxImages +
        'dwp-bar-right.png" class="barRight">' +
        '</div>' +
        '</a>' +
        '</div>';
        
        return PS3Player;
    }    
    
    /* Faux DWP for Mobile devices */
    this.createMobilePlayer = function(){
    
        /* Populate default */
        
        /* Error handling for no previewImage being specified */
        if (this.previewImage == null || this.previewImage.length == 0) {
            var previewImageCode = '<img src="' + fauxImages + 'no-preview-image.png" width="100%" class="previewImage"/>';
        }
        else {
            var previewImageCode = '<img src="' + this.previewImage + '" width="100%" class="previewImage"/>';
        }
        
        var popupDialog = fauxImages + 'popup-dialog.png';
        var popupMessage = "<h1>Save Video For Later</h1>" +
        "<p>This devices does not support playback of DivX files. Tweet or email this video to watch it later or share with your friends.</p>" +
        "<input type='button' value='Tweet' onclick='tweetThis()' class='tweetThis'>" +
        "<input type='button' value='Email' onclick='emailMe()' class='emailMe'>";
        
        var mobilePlayer = '<div style="width: ' + this.width + 'px;" class="fauxPlayer">' +
        '<a class="directLink">' +
        '<div class="popupHolder">' +
        '<div class="popup">' +
        '<div class="message">' +
        popupMessage +
        '</div>' +
        '<img src="' +
        fauxImages +
        'popup-dialog.png" class="dialog">' +
        '</div>' +
        '</div>' +
        previewImageCode +
        '<div class="bar">' +
        '<img src="' +
        fauxImages +
        'dwp-bar-left.png" class="barLeft">' +
        '<img src="' +
        fauxImages +
        'dwp-bar-right.png" class="barRight">' +
        '</div>' +
        '</a>' +
        '</div>';
        return mobilePlayer;
    }
    
    // "Regular" DWP Embed
    this.createStandardPlayer = function(){
        /* Set Defaults */
        if (!this.autoPlay || this.autoPlay == '') 
            this.autoPlay = 'false';
        if (!this.loop || this.loop == '') 
            this.loop = 'false';
        if (!this.mode || this.mode == '') 
            this.mode = 'mini';
        if (!this.minVersion || this.minVersion == '') 
            this.minVersion = '1.5.0';
        if (!this.allowContextMenu || this.allowContextMenu == '') 
            this.allowContextMenu = 'true';
        if (!this.bannerEnabled || this.bannerEnabled == '') 
            this.bannerEnabled = 'true';
        /*if(!this.bufferingMode || this.bufferingMode=='')   
         this.bufferingMode ='auto';*/
        if (!this.movieTitle) 
            this.movieTitle = '';
        if (!this.previewMessage) 
            this.previewMessage = '';
        if (!this.previewMessageSize || this.previewMessageSize == '') 
            this.previewMessageSize = '14';
        
        /* Generate the code */
        var StandardPlayer = '<div id="' + this.playerContainer + '" class="divjsPlayerContainer" style= "height:' + this.height + 'px;" >';
        StandardPlayer += '<object id="' + this.playerContainer + '_ie_plugin" width="' + this.width;
        StandardPlayer += '" height="' + this.height + '" codebase="http://go.divx.com/plugin/DivXBrowserPlugin.cab" classid="clsid:67DABFBF-D0AB-41fa-9C46-CC0F21721616">';
        StandardPlayer += '<param name="src" value="' + this.url + '"/>';
        StandardPlayer += '<param name="autoPlay" value="' + this.autoPlay + '"/>';
        StandardPlayer += '<param name="loop" value="' + this.loop + '"/>';
        StandardPlayer += '<param name="mode" value="' + this.mode + '"/>';
        StandardPlayer += '<param name="bannerEnabled" value="' + this.bannerEnabled + '"/>';
        StandardPlayer += '<param name="minVersion" value="' + this.minVersion + '"/>';
        StandardPlayer += '<param name="allowContextMenu" value="' + this.allowContextMenu + '"/>';
        //StandardPlayer +='<param name="bufferingMode" value="' + this.bufferingMode +'"/>';  
        StandardPlayer += '<param name="bufferingMode" value="auto"/>';
        if (this.movieTitle != '') 
            StandardPlayer += '<param name="movieTitle" value="' + this.movieTitle + '"/>';
        if (this.previewMessage != '') {
            StandardPlayer += '<param name="previewMessage" value="' + this.previewMessage + '"/>';
            StandardPlayer += '<param name="previewMessageSize" value="' + this.previewMessageSize + '"/>';
        }
        StandardPlayer += '<param name="timeCallback" value="dwpEmbedCollection.embedList[' + this.embedCollectionId + '].timeCallback" /> ';
        StandardPlayer += '<param name="statusCallback" value="dwpEmbedCollection.embedList[' + this.embedCollectionId + '].statusCallback" /> ';
        StandardPlayer += '<param name="previewImage" value="' + this.previewImage + '"/>';
        StandardPlayer += '<embed timeCallback="dwpEmbedCollection.embedList[' + this.embedCollectionId + '].timeCallback"';
        StandardPlayer += 'statusCallback="dwpEmbedCollection.embedList[' + this.embedCollectionId + '].statusCallback" id="';
        StandardPlayer += this.playerContainer + '_np_plugin" width="' + this.width + '" height="' + this.height + '" src="';
        StandardPlayer += this.url + '" previewImage="' + this.previewImage + '" type="video/divx" pluginspage="http://go.divx.com/plugin/download/" ';
        
        StandardPlayer += 'autoPlay="' + this.autoPlay + '" ';
        StandardPlayer += 'loop="' + this.loop + '" ';
        StandardPlayer += 'mode="' + this.mode + '" ';
        StandardPlayer += 'bannerEnabled="' + this.bannerEnabled + '" ';
        StandardPlayer += 'minVersion="' + this.minVersion + '" ';
        StandardPlayer += 'allowContextMenu="' + this.allowContextMenu + '" ';
        //StandardPlayer +='bufferingMode="' + this.bufferingMode +'" ';  
        StandardPlayer += 'bufferingMode="auto" ';
        if (this.movieTitle != '') 
            StandardPlayer += 'movieTitle" value="' + this.movieTitle + '" ';
        if (this.previewMessage != '') {
            StandardPlayer += 'previewMessage="' + this.previewMessage + '" ';
            StandardPlayer += 'previewMessageSize="' + this.previewMessageSize + '" ';
        }
        StandardPlayer += '/></object></div><div class="divjsAdContainer" id="' + this.adContainer + '" style="width:';
        StandardPlayer += this.width + 'px;"></div><br clear=all>  ';
        return StandardPlayer;
    }
    
    
    
    this.detectBrowser = function(){
        var userAgent = navigator.userAgent;
        var platform = navigator.platform;
        
        /* Set browser type */
        if (userAgent.search(/playstation/i) != -1 || get('mode') == 'ps3') {
            this.type = 'ps3';
        }
        else 
            if (userAgent.search(/webOS/i) != -1 ||
            userAgent.search(/iPhone/i) != -1 ||
            userAgent.search(/iPad/i) != -1 ||
            userAgent.search(/android/i) != -1 ||
            userAgent.search(/BlackBerry/i) != -1 ||
            get('mode') == 'mobile') {
                this.type = 'mobile'
            }
            else 
                if (platform.search(/Linux/i) != -1) {
                    this.type = 'linux';
                }
                else {
                    this.type = 'standard';
                }
        
        
    }
    
    this.detectWebPlayerPlugin = function(){
        dwpPlugin = new Object;
        dwpPlugin.version = "None";
        dwpPlugin.installed = false;
        
        var userAgent = navigator.userAgent;
        if (userAgent.search(/msie/i) != -1) // If IE
        {
            var dwp = null;
            try {
                dwp = new ActiveXObject('npdivx.DivXBrowserPlugin.1');
            } 
            catch (e) {
            }
            
            if (dwp) {
                dwpPlugin.version = dwp.GetVersion();
                dwpPlugin.installed = true;
            }
            
        }
        else // Else every other browser
        {
            if (navigator.plugins != null && navigator.plugins.length > 0) {
                plugins = navigator.plugins;
                for (var i = 0; i < plugins.length; i++) {
                    // Search for DivX Web Player and version number
                    var re = /DivX(?: | Plus )Web Player[a-z ]*([0-9.]*)/;
                    var results = re.exec(plugins[i].description);
                    if (results) {
                        dwpPlugin.installed = true;
                        dwpPlugin.version = results[1];
                        
                        // End search
                        i = plugins.length;
                    }
                }
            }
        }
        return dwpPlugin
    }
    
    this.offerWebPlayerDownload = function(isInstalled){
        var previewImageCode = '<img src="' + fauxImages + 'no-preview-image.png" width="100%" class="previewImage"/>';
        if (Boolean(isInstalled) == false) {
            var msg = "DivX Plus Web Player not found!";
        }
        else {
            var msg = "Update required";
        }
        var popupMessage = "<h1>" + msg + "</h1>" +
        "<p>Download the latest version of DivX Plus Web Player in order to watch this video.</p>" +
        '<div class="divx-plus-button-download-fix"><div class="btn_download"><a href="http://divx.com/downloads/divx/1" class="download">' +
        'Free Download</a></div></div>';
        var popupDialog = fauxImages + 'popup-dialog.png';
        var downloadPlayer = '<div style="width: ' + this.width + 'px;" class="fauxPlayer">' +
        '<a class="directLink">' +
        '<div class="popupHolder">' +
        '<div class="popup">' +
        '<div class="message">' +
        popupMessage +
        '</div>' +
        '<img src="' +
        fauxImages +
        'popup-dialog.png" class="dialog">' +
        '</div>' +
        '</div>' +
        previewImageCode +
        '<div class="bar">' +
        '<img src="' +
        fauxImages +
        'dwp-bar-left.png" class="barLeft">' +
        '<img src="' +
        fauxImages +
        'dwp-bar-right.png" class="barRight">' +
        '</div>' +
        '</div>';
        return downloadPlayer;
    }
    
    this.setMissingValues = function(){
        if (this.width < 100 || this.width == undefined) 
            this.width = 400;
        if (this.height < 66 || this.height == undefined) 
            this.height = 300;
    }
    
    this.setDivDimension = function(divId){
        if (obj = document.getElementById(divId)) {
            obj.style.width = this.width + 'px';
            obj.style.height = this.height + 'px';
        }
    }
    
    this.populateDiv = function(divId, htmlCode){
        if (this.type == "ps3" || this.type == "mobile") {
            document.write(htmlCode);
        }
        else {
            /* This doesn't work on the PS3. */
            $(document).ready(function(){
                if (obj = document.getElementById(divId)) 
                    obj.innerHTML = htmlCode;
            });
        }
        
    }
    
    /* Callbacks Section */
    
    this.initCallback = function(id){
        if (navigator.userAgent.indexOf('MSIE') != -1 || navigator.userAgent.indexOf('Safari') != -1) {
            this.plugin = document.getElementById(this.playerContainer + '_ie_plugin');
        }
        else {
            this.plugin = document.getElementById(this.playerContainer + '_np_plugin');
        }
        dwpEmbedCollection.embedList[id] = this;
        
    }
    
    this.timeCallback = function(timeSec){
        if (this.adStartOffsetSeconds == timeSec) 
            this.showAd();
    }
    
    this.statusCallback = function(status){
        switch (status) {
        
            case '2': /* VIDEO_END */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics :VIDEO_END');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'VIDEO_END', this.url);
                }
                break;
            case '4': /* EMBEDDED_START */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics : EMBEDDED_START ');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'EMBEDDED_START', this.url);
                }
                break;
                
            case '6': /* WINDOWED_START  */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics : WINDOWED_START ');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'WINDOWED_START', this.url);
                }
                break;
                
            case '8': /* FULLSCREEN_START  */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics : FULLSCREEN_START ');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'FULLSCREEN_START', this.url);
                }
                this.isFullScreen = true;
                
                break;
                
            case '8': /* FULLSCREEN_END  */
                this.isFullScreen = false;
                
                break;
                
            case '10': /*STATUS_PLAYING*/
                /* Now the clip start playing, the total time is available
             *  it's time to calculate the offset for the ad to show (seconds)
             */
                this.debug('Playback started');
                
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics:STATUS_PLAYING');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'STATUS_PLAYING', this.url);
                }
                
                if (this.enableAdvertisement == true) {
                    var clipTotalTime = this.plugin.GetTotalTime();
                    this.adStartOffsetSeconds = parseInt(this.adStartOffsetPercent * clipTotalTime / 100);
                    if (this.adStartOffsetSeconds == 0) 
                        this.adStartOffsetSeconds = 1;
                    this.debug('Advertisement loaded from:' + this.adRequestUrl);
                    this.debug('Ad will be displayed at timecode = ' + this.adStartOffsetSeconds);
                }
                
                break;
            case '11': /*Paused*/
                this.debug('Playback Paused');
                
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics :STATUS_PAUSED');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'STATUS_PAUSED', this.url);
                }
                break;
                
            case '12': /* STATUS_FF   */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics : STATUS_FF ');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'STATUS_FF', this.url);
                }
                break;
                
            case '13': /* STATUS_RW    */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics : STATUS_RW ');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'STATUS_RW', this.url);
                }
                break;
                
            case '14': /* STATUS_STOPPED */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics : STATUS_STOPPED ');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'STATUS_STOPPED', this.url);
                }
                break;
                
            case '15': /*Buffering Start*/
                this.debug('Buffering Started');
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics :BUFFERING_START');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'BUFFERING_START', this.url);
                }
                break;
                
            case '17': /* DOWNLOAD_START */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics : DOWNLOAD_START ');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'DOWNLOAD_START', this.url);
                }
                break;
                
            case '18': /* DOWNLOAD_FAILED  */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics : DOWNLOAD_FAILED ');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'DOWNLOAD_FAILED', this.url);
                }
                break;
                
            case '19': /* DOWNLOAD_DONE   */
                if (this.pageTracker) {
                    /* Ping analytics */
                    this.debug('Ping Google Analytics : DOWNLOAD_DONE ');
                    this.pageTracker._trackEvent('DivX Plus Embed', 'DOWNLOAD_DONE', this.url);
                }
                break;
        }
        
        dwpEmbedCollection.embedList[this.embedCollectionId] = this;
    }
    
    /* Load Bit.ly library */
    this.loadBit_ly = function(login, apikey){
        if (!login || !apikey) {
            login = 'divxweb';
            apikey = 'R_2f7f722881ef474a1df6fb1015fa634a';
        }
        scrUrl = 'http://bit.ly/javascript-api.js?version=3.0&login=' + login + '&apiKey=' + apikey;
        document.write("<script type='text/javascript' src='" + scrUrl + "'></script>");
    }
    
    /* Advertisement Section */
    
    this.populateAdCode = function(adContainer, adHtml){
        $(document).ready(function(){
            $(adContainer).html(adHtml);
            $(adContainer).hover(function(){
                $(this).children('.timeLeftMessage').stop().css("top", "0px");
            }, function(){
                $(this).children('.timeLeftMessage').stop().animate({
                    "top": '400px'
                }, 600);
            });
        });
    }
    
    
    this.loadAdUnit = function(){
    
        if (!this.adType) 
            this.adType = 'all';
        curQry = 'type=' + this.adType;
        if (this.adLanguage) 
            curQry += '&adLanguage=' + this.adLanguage;
        if (this.adCampaign) 
            curQry += '&adCampaign=' + this.adCampaign;
        this.jsonp(this.adServer, 'dwpEmbedCollection.embedList[' + this.embedCollectionId + '].adLoadCallback', curQry);
    }
    
    this.adLoadCallback = function(data){
        adHtml = data.adHtml;
        this.adUnitId = data.adUnitId;
        this.adCampaign = data.adCampaign;
        this.adLanguage = data.adLanguage;
        adHtml += '<span id="dpwp-msg_' + this.adContainer + '" class="timeLeftMessage"></span>';
        this.adDuration = data.adDuration;
        this.adStartOffsetPercent = data.adStartOffsetPercent;
        adContainer = "#" + this.adContainer;
        this.populateAdCode(adContainer, adHtml);
        dwpEmbedCollection.embedList[this.embedCollectionId] = this;
    }
    
    this.makeVisible = function(id){
        if (obj = document.getElementById(id)) 
            obj.style.visibility = 'visible';
    }
    
    this.makeHidden = function(id){
        if (obj = document.getElementById(id)) 
            obj.style.visibility = 'hidden';
    }
    
    this.updateAdMessage = function(){
        this.timeLeft = this.timeLeft - 1;
        if (!this.videoResumeOverlayText) {
            timeLeftText = 'Your presentation will resume in &&TIMELEFT&& seconds';
        }
        else 
            timeLeftText = this.videoResumeOverlayText;
        timeLeftText = timeLeftText.replace('&&TIMELEFT&&', this.timeLeft);
        
        $('#dpwp-msg_' + this.adContainer).text(timeLeftText);
        if (this.timeLeft <= 0) {
            clearInterval(this.intervalHandle);
            this.showPlayer();
        }
        dwpEmbedCollection.embedList[this.embedCollectionId] = this;
    }
    
    this.showAd = function(){
        if (this.adShown == true) 
            return;
        this.adShown = true;
        this.debug("Show Ad");
        if (this.isFullScreen == true) { //the player is in fullscreen mode
            this.debug('Fullscreen mode is on, will resume fulscreen mode after advertisement');
            this.plugin.GoEmbedded();
        }
        $('#' + this.adContainer).show();
        
        this.debug("Hide Player");
        this.makeHidden(this.playerContainer);
        this.plugin.Pause();
        this.debug("Movie Paused");
        this.timeLeft = this.adDuration;
        this.intervalHandle = setInterval('dwpEmbedCollection.embedList[' + this.embedCollectionId + '].updateAdMessage();', 1000);
        if (this.pageTracker) {
            /* Ping analytics */
            this.debug('Ping Google Analytics :ADVERTISEMENT_START');
            this.pageTracker._trackEvent('DivX Plus Embed', 'ADVERTISEMENT_START', 'adCampaign:' + this.adCampaign + ' adUnitId:' + this.adUnitId);
        }
        
    }
    
    this.showPlayer = function(){
        this.debug("Hide Ad");
        $('#' + this.adContainer).hide();
        if (this.isFullScreen == true) { //the playback was in fullscreen mode    
            this.debug('Going back to Fullscreen');
            dwpEmbedCollection.embedList[this.embedCollectionId].plugin.GoFullscreen();
        }
        this.debug("Show Player");
        this.makeVisible(this.playerContainer);
        this.debug("Resume Playback");
        dwpEmbedCollection.embedList[this.embedCollectionId].plugin.Play();
        
        if (this.pageTracker) {
            /* Ping analytics */
            this.debug('Ping Google Analytics :ADVERTISEMENT_END');
            this.pageTracker._trackEvent('DivX Plus Embed', 'ADVERTISEMENT_END', 'adId:' + this.adUnitId);
        }
        
    }
    
    /* Util Section */
    this.jsonp = function(url, callback, query){
    
        if (url.indexOf("?") > -1) 
            url += "&jsonp="
        else 
            url += "?jsonp="
        url += callback + "&";
        if (query) 
            url += query + "&";
        url += new Date().getTime().toString(); // prevent caching        
        var script = document.createElement("script");
        script.setAttribute("src", url);
        script.setAttribute("type", "text/javascript");
        document.body.appendChild(script);
        dwpEmbedCollection.embedList[this.embedCollectionId].adRequestUrl = url;
    }
    this.debug = function(txt){
        txtarea = document.getElementById(this.embedDiv + '_dwpjsConsole');
        if (txtarea) {
            txtarea.value += txt + "\n";
            txtarea.scrollTop = txtarea.scrollHeight;
        }
        
    }
    this.isset = function(parameterValue){
        return parameterValue && parameterValue.length > 0;
    }
    
}


window.onload = function(){
    dwpEmbedCollection.initAllCallbacks();
}


function emailMe(){
    var link = window.location;
    var emailAddress = "";
    var subject = 'DivX Plus Web Player Video';
    var body = 'Enjoy your video: ' + link + '%0A%0A' +
    '- Your Friends at DivX';
    var mailToLink = 'mailto:' + emailAddress +
    '?subject=' +
    subject +
    '&body=' +
    body;
    window.location = mailToLink;
}

function tweetThis(){
    BitlyClient.shorten(document.location, 'BitlyCB.myShortenCallback');
    
    BitlyCB.myShortenCallback = function(data){
        var result;
        for (var r in data.results) {
            result = data.results[r];
            result['longUrl'] = r;
            break;
        }
        
        // Set url for Twitter post
        var twitterURL = "http://twitter.com/home?status=";
        var hashTag = ' #divxweb';
        var status = 'Watch this DivX video online. ' + result['shortUrl'] + hashTag;
        
        window.location = twitterURL + urlEncode(status);
    }
}

// http://www.netlobo.com/url_query_string_javascript.html
function get(name){
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null) 
        return "";
    else 
        return results[1];
}

// http://meyerweb.com/eric/tools/dencoder/
function urlEncode(unencoded){
    return encodeURIComponent(unencoded);
}

function urlDecode(encoded){
    return decodeURIComponent(encoded.replace(/\+/g, " "));
}

function varDump(varToDump){
    for (var k in varToDump) {
        document.write(k + '=' + varToDump[k]);
    }
    
}


